(async () => {
  const utilsUrl = chrome.runtime.getURL('utils.js');
  console.log('utilsUrl:', utilsUrl);
  let utils = await import(utilsUrl);

  // Make utils functions available globally for this script
  window.toPureNumber = utils.toPureNumber;
  window.extractTextFromNode = utils.extractTextFromNode; 
  window.extractNumberFromNode = utils.extractNumberFromNode;
  window.getNodeByXPath = utils.getNodeByXPath;
  window.getNodesByXPath = utils.getNodesByXPath;
  window.getAllTextContent = utils.getAllTextContent;
  window.extractKeyValuePairs = utils.extractKeyValuePairs;
  window.extractTableData = utils.extractTableData;
  window.getXPathAttributeValue = utils.getXPathAttributeValue;

  initContentScript();
})();

function initContentScript() {
  // 测试utils.js函数调用
  console.log('Testing utils.js functions...');
  
  // 测试toPureNumber
  const testNumber1 = toPureNumber('100万');
  const testNumber2 = toPureNumber('1.5亿');
  console.log('toPureNumber:', { 
    '100万': testNumber1, 
    '1.5亿': testNumber2 
  });
  
  // 测试getNodeByXPath
  const bodyNode = getNodeByXPath('//body');
  console.log('getNodeByXPath:', bodyNode ? 'Success' : 'Failed');
  
  console.log('Utils.js function tests completed');

}

// 注册消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'scrollPage') {
    console.log('Received request to scroll page');
    const isAtBottom = (window.innerHeight + window.scrollY) >= document.body.scrollHeight - 10;  // 10px 缓冲，避免误判。因为有可能浮点运算误差导致永远滚不到底
    
    if (!isAtBottom) {
      window.scrollBy({
        top: window.innerHeight,
        behavior: 'smooth'
      });
      sendResponse({ status: 'Scrolling' });
    } else {
      sendResponse({ status: 'Scrolled to end' });
    }
  }
  else if (request.action === 'switchPage') {
    console.log('Received request to switch page');
    
    const nextPageButton = getNodeByXPath('//span[@class="s-pagination-strip"]//a[text()="Next"]');
    if (nextPageButton) {
      nextPageButton.click();
      console.log('Found next page button');
      sendResponse({ status: 'Switching page' });
    } else {
      console.log('Next page button not found');
      sendResponse({ status: 'Switched to end' });
    }
    
  }
  // 处理消息extractAmazonProductDetail
  else if (request.action === 'extractAmazonProductDetail') {
    function getProductDetailAsin() {
      const url = window.location.href;
      const match = url.match(/amazon.com.*\/dp\/([a-zA-Z0-9]{10})\/?/);
      return match ? match[1] : null;
    }
    function getProductDetailTitle() {
      const titleNode = getNodeByXPath('//span[@id="productTitle"]');
      const title = extractTextFromNode(titleNode);
      return title ? title.trim() : null;
    }
    function getProductDetailBrand() {
      const brandNode = getNodeByXPath('//a[starts-with(text(), "Brand:")]');
      const brand = extractTextFromNode(brandNode);
      return brand ? brand.replace('Brand:', '').trim() : null;
    }
    function getProductDetailStore() {
      const storeNode = getNodeByXPath('//a[starts-with(text(), "Visit the")]');
      const store = extractTextFromNode(storeNode);
      return store ? store.replace('Visit the', '').replace('Store', '').trim() : null;
    }
    function getProductDetailStars() {
      const starsValue = getXPathAttributeValue('//span[contains(@title, "out of")]/attribute::title');
      let stars = 0;
      if (starsValue) {
        stars = toPureNumber(starsValue.split(' ')[0]);
      }
      return stars;
    }
    function getProductDetailRatings() {
      const ratingsNode = getNodeByXPath('//a[@id="acrCustomerReviewLink"]/span');
      const ratingsText = extractTextFromNode(ratingsNode);
      let ratings;
      if (ratingsText) {
        ratings = toPureNumber(ratingsText.split(' ')[0].replace(',', ''));
      }
      return ratings;
    }
    function getProductDetailSoldMonth() {
      const soldMonthNode = getNodeByXPath('//span[contains(text(), "bought")]/following-sibling::span[contains(text(), "in past month")]/preceding-sibling::span[1]');
      let soldMonth = 0;
      if (soldMonthNode) {
        const soldMonthText = extractTextFromNode(soldMonthNode);
        if (soldMonthText) {
          const match = soldMonthText.match(/(\d+)(K)?/);
          if (match) {
            soldMonth = match[2] ? toPureNumber(match[1]) * 1000 : toPureNumber(match[1]);
          }
        }
      }
      return soldMonth;
    }
    function getProductDetailProductInformation() {
      const productInformation = extractKeyValuePairs('//div[@id="prodDetails"]//table[starts-with(@id, "productDetails_detailBullets_")]/tbody/tr', './th', './td');
      return productInformation
    }
    function getProductDetailPrice() {
      const priceNode = getNodeByXPath('//div[@id="corePriceDisplay_desktop_feature_div"]//span[@class="aok-offscreen"]');
      const price = extractNumberFromNode(priceNode);
      return price;
    }
    function getProductDetailBulletPoints() {
      const bulletPoints = [];
      const bulletPointNodes = getNodesByXPath('//div[@id="feature-bullets"]//ul/li');
      for (let i = 0; i < bulletPointNodes.snapshotLength; i++) {
        const bulletPoint = getAllTextContent(bulletPointNodes.snapshotItem(i));
        if (bulletPoint) {
          bulletPoints.push(bulletPoint);
        }
      }
      return bulletPoints;
    }
    function getProductDetailLandingImage() {
      const image = getXPathAttributeValue('//*[@id="landingImage"]/attribute::src');
      return image;
    }
    const asin = getProductDetailAsin();
    const title = getProductDetailTitle();
    const brand = getProductDetailBrand();
    const store = getProductDetailStore();
    const stars = getProductDetailStars();
    const ratings = getProductDetailRatings();
    const soldMonth = getProductDetailSoldMonth();
    const productInformation = getProductDetailProductInformation();
    const price = getProductDetailPrice();
    const bulletPoints = getProductDetailBulletPoints();
    const landingImage = getProductDetailLandingImage();
    const result = { asin, title, brand, store, stars, ratings, soldMonth, productInformation, price, bulletPoints, landingImage };
    console.log('extractAmazonProductDetail:', result);
    sendResponse({ result });
  }
  else if (request.action === 'getAllSearchResultsLink') {
    try {
      const xpath = '//div[@role="listitem"][@data-asin]';
      const nodes = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      const links = [];
      
      for (let i = 0; i < nodes.snapshotLength; i++) {
        const node = nodes.snapshotItem(i);
        const sponsor = getNodeByXPath('.//span[text() = "Sponsored"]', node);
        if (!sponsor) {
          const path = getXPathAttributeValue('.//div[@data-cy="title-recipe"]/a/attribute::href', node);
          links.push(`${window.location.protocol}//${window.location.host}${path}`);
        }
      }
      
      console.log('Extracted search result links:', links);
      sendResponse(links.length > 0 ? links : []);
    } catch (error) {
      console.error('Error getting search result links:', error);
      sendResponse([]);
    }
  }
  else if (request.action === 'getAllReviewColorSizes') {
    // Extract all texts by xpath and save to response.result: //a[@data-hook="format-strip"]/text()
    const nextPageButton = getNodeByXPath('//ul[@class="a-pagination"]/li[@class="a-last"]/a');
    if (!nextPageButton) {
      sendResponse({ success: false, error: 'No next page button found' });
      return;
    }
    const xpath = '//a[@data-hook="format-strip"]';
    const colorSizeNodes = getNodesByXPath(xpath);
    const texts = []
    for (let i = 0; i < colorSizeNodes.snapshotLength; i++) {
      const colorSize = getAllTextContent(colorSizeNodes.snapshotItem(i));
      if (colorSize) {
        texts.push(colorSize);
      }
    }
    console.log('Extracted all review color sizes:', texts);
    // Click button to show next page if exist: //ul[@class="a-pagination"]/li[@class="a-last"]/a
    nextPageButton.click();
    sendResponse({ success: true, result: texts });
  }
  else if (request.action === 'copyToClipboard') {
    console.log(request.text);
    navigator.clipboard.writeText(request.text);
    console.log('Copied to clipboard:', request.text);
    sendResponse({ success: true });
  }
});

console.log('Content script loaded successfully');
